﻿using System.Runtime.Loader;

namespace Fantasy.Model;

public static class AssemblyHelper
{
    private const string HotfixDllName = "Hotfix";

    //可空类型
    private static AssemblyLoadContext? _assemblyLoadContext = null;

    private struct AssemblyName
    {
        public const int Model = 1;
        public const int Hotfix = 1;
    }

    public static void Initialize()
    {
        //Model
        AssemblyManager.Load(AssemblyName.Model, typeof(AssemblyHelper).Assembly);
        //Hotfix
        LoadHotfixDll();
    }

    public static void LoadHotfixDll()
    {
        if (_assemblyLoadContext != null)
        {
            _assemblyLoadContext.Unload();
            System.GC.Collect();
        }

        _assemblyLoadContext = new AssemblyLoadContext(HotfixDllName, true);
        var dllBytes = File.ReadAllBytes(Path.Combine(Environment.CurrentDirectory, $"{HotfixDllName}.dll"));
        var pdbBytes = File.ReadAllBytes(Path.Combine(Environment.CurrentDirectory, $"{HotfixDllName}.pdb"));
        var assembly = _assemblyLoadContext.LoadFromStream(new MemoryStream(dllBytes), new MemoryStream(pdbBytes));
        AssemblyManager.Load(AssemblyName.Hotfix, assembly);
    }
}